package com.app.activity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.IdRes;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.app.Application;
import com.app.R;
import com.app.constant.AlipayConstants;
import com.app.constant.Constants;
import com.app.http.HttpDataLoader;
import com.app.http.HttpDataReqUrl;
import com.app.model.bean.Order;
import com.app.model.bean.PayResult;
import com.app.model.bean.User;
import com.app.model.request.ChargeReq;
import com.app.model.response.ResObj;
import com.app.utils.LoginUtil;
import com.app.utils.OrderInfoUtil2_0;
import com.app.utils.ToastUtil;
import com.app.view.ClearWriteEditText;
import com.umeng.analytics.MobclickAgent;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;


public class ActivityCharge extends ActivityBaseCompat {

    private static final String LOG_TAG = ActivityCharge.class.getSimpleName();

    @BindView(R.id.etContent)
    ClearWriteEditText etContent;
    @BindView(R.id.radioGroupPayChannel)
    RadioGroup radioGroupPayChannel;

    private HttpDataLoader dataLoader;

    private int payType = Order.PAY_TYPE_ALIPAY;

    private float totalAmount = 1000.00f;

    private static final int SDK_PAY_FLAG = 1;

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        Toast.makeText(ActivityCharge.this, "支付成功", Toast.LENGTH_SHORT).show();
                        charge();
                        Map<String, String> map_value = new HashMap<String, String>();
                        map_value.put("金额" , String.valueOf(totalAmount));
                        map_value.put("页面" , "充值");
                        map_value.put("详情" , resultInfo);
                        User user = LoginUtil.getLoginUser();
                        if (user != null) {
                            map_value.put("账号" , user.getPhone());
                        }
                        MobclickAgent.onEventValue(Application.instance, "alipaySuccess" , map_value, (int)totalAmount);
//                        MobclickAgent.onEvent(Application.instance, "alipaySuccess");
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        Toast.makeText(ActivityCharge.this, "支付失败", Toast.LENGTH_SHORT).show();
                        Map<String, String> map_value = new HashMap<String, String>();
                        map_value.put("金额" , String.valueOf(totalAmount));
                        map_value.put("页面" , "充值");
                        map_value.put("详情" , resultInfo);
                        User user = LoginUtil.getLoginUser();
                        if (user != null) {
                            map_value.put("账号" , user.getPhone());
                        }
                        MobclickAgent.onEventValue(Application.instance, "alipayFail" , map_value, (int)totalAmount);
//                        MobclickAgent.onEvent(Application.instance, "alipayFail");
                    }
                    break;
                }
                default:
                    break;
            }
        }

        ;
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_charge);
        ButterKnife.bind(this);
        setTitle("充值");
        dataLoader = new HttpDataLoader(this);
        radioGroupPayChannel.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
                switch (checkedId) {
                    case R.id.radioAlipay:
                        payType = Order.PAY_TYPE_ALIPAY;
                        break;
                    case R.id.radioWeChatpay:
                        payType = Order.PAY_TYPE_WECHATPAY;
                        break;
                    default:
                        break;
                }
            }
        });
    }

    private void charge() {
        ChargeReq req = new ChargeReq();
        req.setAmount(Double.valueOf(etContent.getText().toString()));
        req.setTime(System.currentTimeMillis());
        req.setPayType(payType);
        dataLoader.POST(HttpDataReqUrl.URL_CHARGE, req);
    }

    /**
     * 支付宝支付业务
     *
     * @param v
     */
    public void payV2(View v) {


        if (TextUtils.isEmpty(AlipayConstants.APPID) || (TextUtils.isEmpty(AlipayConstants.RSA2_PRIVATE) && TextUtils.isEmpty(AlipayConstants.RSA_PRIVATE))) {
            new AlertDialog.Builder(this).setTitle("警告").setMessage("需要配置APPID | RSA_PRIVATE")
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialoginterface, int i) {
                            //
                            finish();
                        }
                    }).show();
            return;
        }

        /**
         * 这里只是为了方便直接向商户展示支付宝的整个支付流程；所以Demo中加签过程直接放在客户端完成；
         * 真实App里，privateKey等数据严禁放在客户端，加签过程务必要放在服务端完成；
         * 防止商户私密数据泄露，造成不必要的资金损失，及面临各种安全风险；
         *
         * orderInfo的获取必须来自服务端；
         */
        boolean rsa2 = (AlipayConstants.RSA2_PRIVATE.length() > 0);
        Map<String, String> params = OrderInfoUtil2_0.buildOrderParamMap(AlipayConstants.APPID, totalAmount, rsa2);
        String orderParam = OrderInfoUtil2_0.buildOrderParam(params);

        String privateKey = rsa2 ? AlipayConstants.RSA2_PRIVATE : AlipayConstants.RSA_PRIVATE;
        String sign = OrderInfoUtil2_0.getSign(params, privateKey, rsa2);
        final String orderInfo = orderParam + "&" + sign;
//        EnvUtils.setEnv(EnvUtils.EnvEnum.SANDBOX);
        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                PayTask alipay = new PayTask(ActivityCharge.this);
                Map<String, String> result = alipay.payV2(orderInfo, true);
                Log.i("msp", result.toString());

                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        Thread payThread = new Thread(payRunnable);
        payThread.start();
        Map<String, String> map_value = new HashMap<String, String>();
        map_value.put("金额" , String.valueOf(totalAmount));
        map_value.put("页面" , "充值");
        User user = LoginUtil.getLoginUser();
        if (user != null) {
            map_value.put("账号" , user.getPhone());
        }
        MobclickAgent.onEventValue(this, "alipay" , map_value, (int)totalAmount);
//        MobclickAgent.onEvent(Application.instance, "alipay");
    }


    @OnClick({R.id.tvCharge})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tvCharge:
                if (etContent.getText() != null && !etContent.getText().toString().equals("")) {
                    totalAmount = Float.valueOf(etContent.getText().toString());
                    if (payType == Order.PAY_TYPE_ALIPAY) {
                        payV2(view);
                    } else {
                        // TODO wechatpay
                    }
                } else {
                    ToastUtil.getInstance().showToast(ActivityCharge.this, "请输入充值金额");
                }
                break;
            default:
                break;
        }

    }


    @Override
    public void onRequestSuccess(String url, ResObj result, boolean isFrmCache) {
        Log.e(LOG_TAG, "onRequestSuccess");
        Log.e(LOG_TAG, "url: " + url);
        Log.e(LOG_TAG, "result: " + result);
        if (url.equals(HttpDataReqUrl.URL_CHARGE)) {
            ToastUtil.getInstance().showToast(this, result.getMsg());
            if (result.getCode() == Constants.CODE_SUCCESS) {
                finish();
            }
        }
    }

    @Override
    public void onRequestError(String url, int statusCode, String error) {
        Log.e(LOG_TAG, "onRequestError");
        Log.e(LOG_TAG, "url: " + url);
        Log.e(LOG_TAG, "statusCode: " + statusCode);
        ToastUtil.getInstance().showToast(this, error);
    }

    @Override
    public void onBackPressed() {
        finish();
        overridePendingTransition(0, R.anim.push_left_out);
    }
}
